<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace App\Base;


use Symfony\Component\HttpFoundation\Request;

class BaseController4Back extends BaseController {

    public $data;
    public $theme = "Sano";

    public function show($template,$data = [],$response = null)
    {
//        $assetsStr = "/themes/sano";
//        $data["assetsRoot"] = $assetsStr;
//        $data["assetsRoot"] = $assetsStr;
//        $data["rnd"] = "?rnd=".time();
//        dd($request);
        $request = Request::createFromGlobals();
        $data["uri"] = $request->getPathInfo();
        $bc = new BaseCache();
        $menu = $bc->getItem("initMenu");
        $data["menu"] = $menu;
        $twigStr = "Back/".$this->theme."/".$template.".html.twig";
        $assetsStr = "/themes/sano";
        $data["assetsRoot"] = $assetsStr;
        $data["rnd"] = "?rnd=".time();
        return $this->render($twigStr,$data,$response);
    }

    public function needToBeLogin()
    {
        header('content-type:application/json');
        header('charset:utf8');
        header('Access-Control-Allow-Origin:*');
        header("HTTP/1.1 200 Non-Authoritative Information");
        $s = 0;
        $i = "请登录后再操作";
        $re = array(
            "s"    => $s,
            "i"    => $i,
            "d"    => [],
        );
        die(json_encode($re));
    }

    public function isAdmin()
    {
        $roles = $this->getUserCache("role");
        if (is_array($roles) && in_array("ROLE_ADMIN",$roles)) {
            return $this->getUserCache("id");
        } else {
            return false;
        }
    }

    public function needToBeAdmin()
    {
        if ($this->isAdmin()) {
            return $this->getUserCache("id");
        } else {
            $this->needToBeLogin();
        }
    }

    public function json_out($s,$i,$d = array())
    {
        $context = [];
        if ($this->groups) {
            $context["groups"] = $this->groups;
        }

        $data = ["s"=>$s,"i"=> $i,"d"=>$d];
        if ($this->meta) {
            $data["meta"] = $this->meta;
        }
        return $this->json($data,200,["content-type"=>"application/json","access-token"=>$this->baseCache->getUserAccessToken(Request::createFromGlobals())],$context);
    }
}
